package com.atguigu.flink.chapter10;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2023/6/27 09:23
 */
public class TableApiDemo2 {
    public static void main(String[] args) throws Exception {
        // 1. 表的执行
        /*EnvironmentSettings conf = EnvironmentSettings.newInstance()
            .inStreamingMode()
            .build();
        TableEnvironment tEnv = TableEnvironment.create(conf);*/
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("s1", 1000L, 10),
            new WaterSensor("s2", 2000L, 20),
            new WaterSensor("s1", 3000L, 30),
            new WaterSensor("s1", 4000L, 40),
            new WaterSensor("s2", 5000L, 50)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream);
        
        // api 的方式: select id, sum(vc) as vc_sum from t group by id;
        Table result = table
            .groupBy($("id"))
            .aggregate($("vc").sum().as("vc_sum"))
            .select($("id"), $("vc_sum"));
    
        /*tEnv.toRetractStream(result, Row.class)
            .filter(t -> t.f0)
            .map(t -> t.f1)
            .print();*/
        
        DataStream<Row> s1 = tEnv
            .toChangelogStream(result);
        
        s1
            .filter(row -> {
                String name = row.getKind().name();
                return "INSERT".equals(name) || "UPDATE_AFTER".equals(name);
            })
            .map(new MapFunction<Row, WaterSensor>() {
                @Override
                public WaterSensor map(Row row) throws Exception {
                    String id = row.getFieldAs("id");
                    Integer vcSum = row.getFieldAs("vc_sum");
                    return new WaterSensor(id, 1L, vcSum);
                }
            })
            .print();
        
        
        env.execute();
    }
}
